// 2025/3/7
// https://leetcode.cn/problems/intersection-of-two-linked-lists/description/?envType=study-plan-v2&envId=top-100-liked
// 相交链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            int countA = 0, countB = 0;
            ListNode *curA = headA, *curB = headB;
            while(curA != nullptr)
            {
                ++countA;
                curA = curA->next;
            }
            while(curB != nullptr)
            {
                ++countB;
                curB = curB->next;
            }
            while(countA < countB)
            {
                --countB;
                headB = headB->next;
            }
            while(countB < countA)
            {
                --countA;
                headA = headA->next;
            }
            while(headA != nullptr && headA != headB)
            {
                headA = headA->next;
                headB = headB->next;
            }
    
            return headA;
        }
    };